<template>
  <div>
    <div class="page-title">账户管理</div>
    
    <el-card>
      <template #header>
        <div class="card-header">
          <span>账户列表</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增账户
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable />
        </el-form-item>
        <el-form-item label="角色"  style="width: 150px;">
          <el-select v-model="searchForm.role" placeholder="请选择角色" clearable>
            <el-option label="管理员" value="admin" />
            <el-option label="美容师" value="beautician" />
            <el-option label="顾客" value="customer" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态"  style="width: 150px;">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 账户列表 -->
      <el-table
        v-loading="loading"
        :data="accountList"
        border
        style="width: 100%"
      >
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="nickname" label="昵称" width="100" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleLabel(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" >
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" text @click="handleResetPwd(row)">
              重置密码
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑账户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增账户' : '编辑账户'"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="accountFormRef"
        :model="accountForm"
        :rules="accountRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="accountForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="accountForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="accountForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="accountForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="accountForm.role" placeholder="请选择角色" >
            <el-option label="管理员" value="admin" />
            <el-option label="美容师" value="beautician" />
            <el-option label="顾客" value="customer" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="accountForm.status">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      v-model="resetPwdDialogVisible"
      title="重置密码"
      width="400px"
      @close="handleResetPwdClose"
    >
      <el-form
        ref="resetPwdFormRef"
        :model="resetPwdForm"
        :rules="resetPwdRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="resetPwdForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPwdForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPwdDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleResetPwdSubmit" :loading="resetPwdLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getAccounts, createAccount, updateAccount, deleteAccount, resetPassword } from '@/api/accounts'

interface Account {
  id?: number
  username: string
  password?: string
  email?: string
  phone?: string
  role: 'admin' | 'beautician' | 'customer'
  status: 0 | 1
  nickname?: string
  createdAt?: string
  updatedAt?: string
}

// 搜索表单
const searchForm = ref({
  username: '',
  nickname: '',
  role: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const accountList = ref<Account[]>([])
const loading = ref(false)

// 对话框数据
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const accountFormRef = ref<FormInstance>()
const accountForm = ref<Account>({
  username: '',
  password: '',
  nickname: '',
  email: '',
  phone: '',
  role: 'beautician',
  status: 1
})

// 重置密码对话框
const resetPwdDialogVisible = ref(false)
const resetPwdFormRef = ref<FormInstance>()
const resetPwdForm = ref({
  newPassword: '',
  confirmPassword: ''
})
const currentAccount = ref<Account | null>(null)
const submitLoading = ref(false)
const resetPwdLoading = ref(false)

// 表单验证规则
const accountRules: FormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
  ],
  realName: [
    { max: 50, message: '长度不超过 50 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const resetPwdRules: FormRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取账户列表
const fetchAccounts = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.pageSize,
      ...searchForm.value
    }
    const response = await getAccounts(params)
    accountList.value = response.records
    pagination.total = response.total
  } catch (error) {
    console.error('获取账户列表失败:', error)
    ElMessage.error('获取账户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchAccounts()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    username: '',
    realName: '',
    role: '',
    status: ''
  }
  handleSearch()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchAccounts()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.current = page
  fetchAccounts()
}

// 新增账户
const handleAdd = () => {
  dialogType.value = 'add'
  accountForm.value = {
    username: '',
    email: '',
    phone: '',
    role: 'beautician',
    status: 1,
    realName: ''
  }
  dialogVisible.value = true
}

// 编辑账户
const handleEdit = (row: Account) => {
  dialogType.value = 'edit'
  accountForm.value = { ...row }
  dialogVisible.value = true
}

// 删除账户
const handleDelete = async (row: Account) => {
  try {
    await ElMessageBox.confirm('确定要删除该账户吗？', '提示', {
      type: 'warning'
    })
    await deleteAccount(row.id!)
    ElMessage.success('删除成功')
    fetchAccounts()
  } catch (error) {
    console.error('删除账户失败:', error)
  }
}

// 状态改变
const handleStatusChange = async (row: Account, status: number) => {
  try {
    await updateAccount(row.id!, { status })
    ElMessage.success('状态更新成功')
    fetchAccounts()
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    row.status = status === 1 ? 0 : 1
  }
}

// 重置密码
const handleResetPwd = (row: Account) => {
  currentAccount.value = row
  resetPwdForm.value = {
    newPassword: '',
    confirmPassword: ''
  }
  resetPwdDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!accountFormRef.value) return
  
  await accountFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await createAccount(accountForm.value)
          ElMessage.success('新增成功')
        } else {
          await updateAccount(accountForm.value.id!, accountForm.value)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        fetchAccounts()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 提交重置密码
const handleResetPwdSubmit = async () => {
  if (!resetPwdFormRef.value || !currentAccount.value) return
  
  await resetPwdFormRef.value.validate(async (valid) => {
    if (valid) {
      resetPwdLoading.value = true
      try {
        await resetPassword(currentAccount.value.id!, resetPwdForm.value.newPassword)
        ElMessage.success('密码重置成功')
        resetPwdDialogVisible.value = false
      } catch (error) {
        console.error('密码重置失败:', error)
      } finally {
        resetPwdLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  accountFormRef.value?.resetFields()
}

// 重置密码对话框关闭
const handleResetPwdClose = () => {
  resetPwdFormRef.value?.resetFields()
  currentAccount.value = null
}

// 角色标签类型
const getRoleType = (role: string) => {
  const typeMap: Record<string, string> = {
    admin: 'danger',
    manager: 'warning',
    beautician: 'success',
    receptionist: 'info'
  }
  return typeMap[role] || 'info'
}

// 角色标签文本
const getRoleLabel = (role: string) => {
  const labelMap: Record<string, string> = {
    admin: '管理员',
    customer: '顾客',
    beautician: '美容师'
  }
  return labelMap[role] || role
}

// 格式化日期
const formatDate = (date?: string) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 页面加载
onMounted(() => {
  fetchAccounts()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>